// pages/myPage/myPage.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    avatarUrl:"",
    status: "",
    userId: "",
    nickName: "",
    phoneNumber: '400-670-2677',
    avatar:"http://file.jwsxmall.com/28.png",
    authStatus:"",
    partnerUserId:'',
    showModal:false,
    setInter: '',
    time: 5,
    choo_modal: "none",
    choo_modal_code: "none",
    img:2,
    code:0
  },
  /**
   * 页面分享
   */
  onShareAppMessage: function () {
    var that = this;
      return {
        title: '极味生鲜',
        desc: '分享页面的内容',
        imageUrl: "http://file.jwsxmall.com/shareImg.jpg",
        path: '/pages/mallPage/mallPage?partnerUserId=' + wx.getStorageSync("userId") , // 路径，传递参数到指定页面
      }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    this.dialog = this.selectComponent("#dialog");
    this.dialog.showDialog();
    if (options.partnerUserId == undefined && wx.getStorageSync("partnerUserId_nlc") == undefined){
      this.setData({
        partnerUserId: 0
      })
    } else if (options.partnerUserId!=undefined){
      this.setData({
        partnerUserId: options.partnerUserId
      })
    } else if (wx.getStorageSync("partnerUserId_nlc") != undefined){
      this.setData({
        partnerUserId: wx.getStorageSync("partnerUserId_nlc")
      })
    }
    
    
    //获取手机高度
    this.setData({
      navH: app.globalData.navHeight,
      isIpx: app.globalData.isIpx,
      modelmes: app.globalData.modelmes,
    })
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    var that = this;
    // var nick = wx.getStorageSync("nickName");
    // var userid = wx.getStorageSync("userId");
    // var phone = wx.getStorageSync("telephone");
    // var avatar = wx.getStorageSync("avatar");
    // var authStatus = wx.getStorageSync("authStatus");
    // var level = wx.getStorageSync("level");
    // var ongoing = wx.getStorageSync("ongoing");
    // var registration = wx.getStorageSync("registration");
    // var completed = wx.getStorageSync("completed");
    // var commissionmoneyamount = wx.getStorageSync("commissionMoneyAmount");
    // var balance = wx.getStorageSync("balance");
    // var points = wx.getStorageSync("points");
    // var roleId = wx.getStorageSync("roleId");
    // console.info(level);
    // if (avatar != 'avatar/defaultUserAvatar.png' && avatar.trim() != "" && avatar.trim() != null) {
    //   this.setData({
    //     avatar: avatar,

    //   })
    // }
    // this.setData({
    //   nickName: nick,
    //   userId: userid,
    //   telephone: phone,
    //   avatarUrl: avatar,
    //   authStatus: authStatus,
    //   level: level,
    //   completed: completed,
    //   registration: registration,
    //   ongoing: ongoing,
    //   points: points,
    //   commissionmoneyamount: commissionmoneyamount,
    //   balance: balance,
    //   roleId: roleId
    //   // avatar: app.globalData.urlFile+avatar
    // })
    //赚钱攻略
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var that = this;
    wx.request({
      url: app.globalData.url + "getParaById?paraId=recharge_flag",
      method: "GET",
      data: {
      },
      success: function (res) {
        if (res.data.result == 1) {
          that.setData({
            recharge: res.data.data.value
          })
        } 
      }
    });
    that.setData({
      token: wx.getStorageSync("token")
    });
    wx.request({
      url: app.globalData.url + "getWebDetail",
      method: "GET",
      data: {
        webId: "getMoney",
        token: that.data.token
      },
      success: function (res) {
        var data = res.data;
        if (data.result == 1) {
          if (res.data.token != "" && res.data.token != undefined) {
            wx.setStorageSync("token", res.data.token)
          }
        }
        if (res.data.result == 9) {
          wx.reLaunch({
            url: '/pages/zcuslist/index?partnerUserId=' + that.data.partnerUserId
          })
          return false;
        }
        that.setData({
          title: data.data.title,
          icon: data.data.icon,
          webId: data.data.webId
        })
      }
    })
    wx.request({
      url: app.globalData.url + "getUserApplyCommunityHeadHis",
      data: {
        userId: wx.getStorageSync("userId")
      },
      method: "GET",
      success: function (res) {
        var data = res.data;
        if (data.result == 1) {
          that.setData({
            headHis: data.data,
          })
        }
      }
    });
    
    wx.request({
      url: app.globalData.url + "userEstimatedRevenue",
      data: {
        userId: wx.getStorageSync("userId")
      },
      method: "GET",
      success: function (res) {
        var data = res.data;
        if (data.result == 1) {
          that.setData({
            lastMonth: data.data.lastMonth,
            month: data.data.month,
            today: data.data.today,
            yesterday: data.data.yesterday
          })
        }
      }
    });
    that.hideModal1();
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          var statu = wx.getStorageSync("status");
          this.setData({
            status: statu,
          })
          wx.request({
            url: app.globalData.url + "getUserByWechatUnoinId",
            method: "GET",
            data: {
              wechatUnoinId: wx.getStorageSync("wechatUnoinId"),
              token: that.data.token,
              phoneModel: app.globalData.modelmes
            },
            success: function (res) {
              var data = res.data;
              if (data.result==1){
                that.setData({
                  code:1
                })
                if (res.data.token != "" && res.data.token != undefined) {
                  wx.setStorageSync("token", res.data.token)
                }
                
                // wx.setStorageSync("userId", data.data.userId);
                wx.setStorageSync("nickName", data.data.nickName);
                wx.setStorageSync("telephone", data.data.telephone);
                wx.setStorageSync("avatar", data.data.avatar);
                wx.setStorageSync("applicationType", data.data.applicationType);
                wx.setStorageSync("authStatus", data.data.authStatus);
                wx.setStorageSync("balance", data.data.balance.toFixed(2));
                wx.setStorageSync("boundWechat", data.data.boundWechat);
                wx.setStorageSync("commissionMoneyAmount", data.data.commissionMoneyAmount);
                wx.setStorageSync("completeNumber", data.data.completeNumber);
                wx.setStorageSync("createTime", data.data.createTime);
                wx.setStorageSync("invitationCode", data.data.invitationCode);
                wx.setStorageSync("inviteUserId", data.data.inviteUserId);
                wx.setStorageSync("parentUserId", data.data.parentUserId);
                wx.setStorageSync("partner", data.data.partner);
                wx.setStorageSync("level", data.data.level);
                wx.setStorageSync("partnerStatus", data.data.partnerStatus);
                wx.setStorageSync("points", data.data.points);
                wx.setStorageSync("promoteUserNumber", data.data.promoteUserNumber);
                wx.setStorageSync("roleId", data.data.roleId);
                wx.setStorageSync("sex", data.data.sex);
                wx.setStorageSync("withdrawWay", data.data.withdrawWay);
                wx.setStorageSync("wechatUnoinId", data.data.wechatUnoinId);
                wx.setStorageSync("telephone", data.data.telephone);
                wx.setStorageSync("commissionmoneyamount", data.data.commissionmoneyamount);
                wx.setStorageSync("ongoing", data.data.ongoing);
                wx.setStorageSync("registration", data.data.registration);
                wx.setStorageSync("completed", data.data.completed);
                wx.setStorageSync("token", data.data.token);
                wx.setStorageSync("awards", data.data.awards);
                wx.setStorageSync("awardsShow", data.data.awardsShow);
                wx.setStorageSync("invitationPrice", data.data.invitationPrice);
                wx.setStorageSync("communityHead", data.data.communityHead);
                wx.setStorageSync("pickUpCode", data.data.pickUpCode);
                wx.setStorageSync("avatarUrl", data.data.avatar);
                wx.setStorageSync("notificaionToRead", data.data.notificaionToRead);
                wx.setStorageSync("noWithdrawBalance", data.data.noWithdrawBalance);
                
                that.setData({
                  pickUpCode: wx.getStorageSync("pickUpCode")
                })
                if (data.data.avatar != 'avatar/defaultUserAvatar.png' && data.data.avatar.trim() != "" && data.data.avatar.trim() != null) {
                  that.setData({
                    avatar: data.data.avatar,
                  })
                }
                that.setData({
                  nickName: data.data.nickName,
                  userId: data.data.userId,
                  telephone: data.data.telephone,
                  avatarUrl: data.data.avatar,
                  authStatus: data.data.authStatus,
                  level: data.data.level,
                  completed: data.data.completed,
                  registration: data.data.registration,
                  ongoing: data.data.ongoing,
                  points: data.data.points,
                  commissionmoneyamount: data.data.commissionmoneyamount,
                  balance: data.data.balance.toFixed(2),
                  roleId: data.data.roleId,
                  communityHead: data.data.communityHead,
                  quitCommunityHeadHis: data.data.quitCommunityHeadHis,
                })
                
              } else {
                console.info(that.data.detailtype);
                wx.reLaunch({
                  url: '/pages/zcuslist/index?partnerUserId=' + that.data.partnerUserId,
                })
              }
            }
          });

          wx.request({
            url: app.globalData.url + "getUserByWechatUnoin",
            method: "GET",
            data: {
              wechatUnoinId: wx.getStorageSync("wechatUnoinId"),
              token: that.data.token
            },
            success: function (res) {
              var data = res.data;
              if (data.result == 1) {
                wx.setStorageSync("awards", data.data.awards);
                wx.setStorageSync("awardsShow", data.data.awardsShow);
                wx.setStorageSync("completedOrder", data.data.completedOrder);
                wx.setStorageSync("invitationPrice", data.data.invitationPrice);
                wx.setStorageSync("paidOrder", data.data.paidOrder);
                wx.setStorageSync("pendingOrder", data.data.pendingOrder);
                wx.setStorageSync("receive", data.data.receive);
                wx.setStorageSync("refundOrder", data.data.refundOrder);
                wx.setStorageSync("shipOrder", data.data.shipOrder);
                that.setData({
                  awards: data.data.awards,
                  awardsShow: data.data.awardsShow,
                  completedOrder: data.data.completedOrder,
                  invitationPrice: data.data.invitationPrice,
                  paidOrder: data.data.paidOrder,
                  pendingOrder: data.data.pendingOrder,
                  receive: data.data.receive,
                  refundOrder: data.data.refundOrder,
                  shipOrder: data.data.shipOrder,
                })
              }
            }
          });
          
        } else {
          // 未授权，跳转到授权页面
          console.info("未授权1" + that.data.partnerUserId);
          wx.reLaunch({
            url: '/pages/zcuslist/index?partnerUserId=' + that.data.partnerUserId,
          })
        }
        var phone = wx.getStorageSync("telephone");
        console.info(phone);
        if (phone == "") {
          that.showModal();
        } else {
          that.hideModal();
        }
      }
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    var that = this;
    clearInterval(that.data.setInter);
    clearInterval(this.data.timer);
    clearInterval(this.data.time);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    var that = this;
    clearInterval(that.data.setInter);
    clearInterval(this.data.timer);
    clearInterval(this.data.time);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 跳转到消息通知
   */
  toMessageNotice: function() {
    wx.navigateTo({
      url: '/pages/messageNotice/messageNotice',
    })
  },


  /**
   * 赚钱攻略
   */
  makeMoney: function(res) {
    wx.navigateTo({
      url: '/pages/webView/webView?url=' + app.globalData.url + 'getWebPage&webId=' + res.currentTarget.dataset.webid,
      //url: '/pages/webView/webView?url=http://47.104.96.96/yixuanqi/getWebPage'
    })
  },
  /**
   * 跳转进行中
   */
  toServiceList:function(){
    wx.navigateTo({
      url: '/pages/myTask/myTask?currentTab=1'
    })
  },
  /**
   * 跳转报名待审核
   */
  toReviewed:function(){
    wx.navigateTo({
      url: '/pages/myTask/myTask?currentTab=2'
    })
  },
  /**
   * 跳转已完成
   */
  toComplete: function () {
    wx.navigateTo({
      url: '/pages/myTask/myTask?currentTab=3'
    })
  },
  groupApply: function () {
    console.info(this.data.headHis+"团长状态");
    if (this.data.communityHead == false&&this.data.headHis.status != 1) {
      wx.navigateTo({
        url: '/pages/communityGroupApply/communityGroupApply'
      })
    } else if(this.data.headHis.status == 1){
      wx.showToast({
        title: '请耐心等待审核！',  // 标题
        icon: 'success',   // 图标类型，默认success
        duration: 3000   // 提示窗停留时间，默认1500ms
      })
    }
  },
  toCommission: function () {
    wx.navigateTo({
      url: '/pages/communityGroupCommission/communityGroupCommission'
    })
  },
  /**
   * 跳转我的钱包
   */
  toMyWallet: function () {
    wx.navigateTo({
      url: '/pages/myWallet/myWallet?userId=' + this.data.userId
    })
  },
  /**
   * 跳转我的提成
   */
  toMyCommission:function(){
    // if(this.data.level == 1){
    //   wx.showToast({
    //     title: '您暂时未成立团队',
    //     icon:"none"
    //   })
    //   return;
    // }
    wx.navigateTo({
      url: '/pages/myCommission/myCommission?userId=' + this.data.userId
    })
  },
  toPointHistory: function () {
    wx.navigateTo({
      url: '/pages/pointHistory/pointHistory?userId=' + this.data.userId
    })
  },
  toBanlance:function(){
    wx.navigateTo({
      url: '/pages/myWallet/myWallet?userId=' + this.data.userId
    })
  },
  payment: function () {
    wx.navigateTo({
      url: '/pages/myOrder/myOrder?type=1'
    })
  },
  toCollection:function(){
    wx.navigateTo({
      url: '/pages/myCollection/myCollection'
    })
  },
  goods: function () {
    wx.navigateTo({
      url: '/pages/myOrder/myOrder?type=2'
    })
  },
  evaluation:function(){
    wx.navigateTo({
      url: '/pages/myOrder/myOrder?type=5'
    })
  },
  complete: function () {
    wx.navigateTo({
      url: '/pages/myOrder/myOrder?type=3'
    })
  },
  after: function () {
    wx.navigateTo({
      url: '/pages/myOrder/myOrder?type=4'
    })
  },
  all: function () {
    wx.navigateTo({
      url: '/pages/myOrder/myOrder?type=0'
    })
  },
  myCoupons: function () {
    wx.navigateTo({
      url: '/pages/myCoupons/myCoupons'
    })
  },
  goRefundAndReplacement: function () {
    wx.navigateTo({
      url: '/pages/refundAndReplacement/refundAndReplacement'
    })
  },
  groupOrder: function () {
    wx.navigateTo({
      url: '/pages/spellGroupOrderList/spellGroupOrderList'
    })
  },
  integralOrderList: function () {
    wx.navigateTo({
      url: '/pages/integralOrderList/integralOrderList'
    })
  },
  toMembers: function () {
    wx.navigateTo({
      url: '/pages/myMembers/myMembers'
    })
  },
  toMembersOrder: function () {
    wx.navigateTo({
      url: '/pages/communityGroupOrder/communityGroupOrder'
    })
  },
  mentionCargo: function () {
    wx.navigateTo({
      url: '/pages/mentionCargo/mentionCargo'
    })
  },
  toWithdrawal: function () {
    var authStatus = wx.getStorageSync("authStatus");
      if (authStatus==2){

        wx.showToast({
          title: '资料审核中',
          icon: 'none',
          duration: 2000
        })
      }else{
        wx.navigateTo({
          url: '/pages/certification/certification?userId=' + this.data.userId
        })
      }
      
    },
  upgradeMembership : function () {
      // wx.navigateTo({
      //   url: '/pages/membershipPrivileges/membershipPrivileges?userId=' + this.data.userId
      // })
  },
  toMyTeam: function (res) {
    // if(this.data.level == 1){
    //   wx.showToast({
    //     title: '成为银牌会员开启此功能',
    //     icon:"none"
    //   })
    //   return;
    // }
    var that = this;
    wx.navigateTo({
      url: '/pages/myTeam/myTeam?userId=' + this.data.userId
    })
  },
  getPhoneNumber: function (e) {
    var ivObj = e.detail.iv
    var telObj = e.detail.encryptedData
    var codeObj = "";
    var that = this;
    //------执行Login
    wx.login({
      success: res => {
        console.log('code转换', res.code); //用code传给服务器调换session_key

        wx.request({
          url: app.globalData.url + 'getPhoneNumber', //接口地址
          data: {
            code: res.code,
            encryptedData: telObj,
            iv: ivObj,
            token: that.data.token
          },
          header: {
            'content-type': 'application/json' // 默认值
          },
          success: function (res) {
            var data = res.data;
            if (data.result == 1) {
              if (res.data.token != "" && res.data.token != undefined) {
                wx.setStorageSync("token", res.data.token)
              }
            }
            if (res.data.result == 9) {
              wx.reLaunch({
                url: '/pages/zcuslist/index',
              })
              return false;
            }
            wx.setStorage({   //存储数据并准备发送给下一页使用
              key: "telephone",
              data: data.userInfo.telephone,
            })
          }
        })
        if (e.detail.errMsg == 'getPhoneNumber:fail user deny') { //用户点击拒绝
          this.hideModal();
        } else { //授权通过执行跳转
          this.hideModal();
        }
      }
    });

    //---------登录有效期检查
    wx.checkSession({
      success: function () {
        //session_key 未过期，并且在本生命周期一直有效
      },
      fail: function () {
        // session_key 已经失效，需要重新执行登录流程
        wx.login() //重新登录
      }
    });
  },
  //显示对话框
  showModal: function () {
    wx.hideTabBar({});
    // 显示遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
      showModalStatus: true
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export()
      })
    }.bind(this), 200)
  },
  //隐藏对话框
  hideModal: function () {
    wx.showTabBar({});
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        showModalStatus: false
      })
    }.bind(this), 200)
  },

  message:function(){
    wx.navigateTo({
      url: '/pages/messageCenter/messageCenter'
    })
  },
  /**
   * 弹出框蒙层截断touchmove事件
   */
  preventTouchMove: function () {
  },

  /**
   * 隐藏模态对话框
   */
  hideModal1: function () {
    var that = this;
    clearInterval(that.data.setInter);
    clearInterval(this.data.timer);
    clearInterval(this.data.time);
    this.setData({
      showModal: false
    })
  },
  gomembershipPrivileges:function(){
    wx.navigateTo({
      url: '/pages/membershipPrivileges/membershipPrivileges'
    })
  },
  goInvoice: function () {
    wx.navigateTo({
      url: '/pages/invoiceApplication/invoiceApplication'
    })
  },
  mentionCargo: function () {
    wx.navigateTo({
      url: '/pages/mentionCargo/mentionCargo',
    })
  },
  toAddress: function () {
    wx.navigateTo({
      url: '/pages/addressList/addressList?myPoint=1',
    })
  },
  onChooseAvatar:function(e){
    var id = wx.getStorageSync("userId");
      if(!id){
        wx.showToast({
          title: '请先授权手机号',
          icon: 'none',     //默认值是success,就算没有icon这个值，就算有其他值最终也显示success
          duration: 1000,      //停留时间
        })
        return;
      }
      const { avatarUrl } = e.detail 
      const hearUrl =  'data:image/png;base64,' + wx.getFileSystemManager().readFileSync(avatarUrl,'base64');
        // 更新数据  
        this.setData({
          avatarUrl: hearUrl
        });
        //保存头像信息
        var id = wx.getStorageSync("userId");
        wx.request({
          url: app.globalData.url + 'updateUserByUserId', //
          data: {
            userId: id,
            avatar: hearUrl,
          },
          method: 'POST',
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          success: function (res) {
            console.log(res.data);
            if (res.data.result == 1) {
              wx.showToast({
                title: '头像修改成功',
                icon: 'none',     //默认值是success,就算没有icon这个值，就算有其他值最终也显示success
                duration: 1000,      //停留时间
              })
            } else if (res.data.result == 0) {
              wx.showToast({
                title: res.data.errmsg,
                icon: 'none',     //默认值是success,就算没有icon这个值，就算有其他值最终也显示success
                duration: 2000,      //停留时间
              })
            } else if (res.cancel) {
              return;
            }
          }
        })
  },
  //跳转个人信息
  toUserInfo: function () {
    wx.navigateTo({
      url: '/pages/userInfo/userInfo',
    })
  },
  toValueCard: function () {
    var that = this;
    if ( that.data.recharge == 1){
      wx.showToast({
        title: '功能暂未开放',  // 标题
        icon: 'none',   // 图标类型，默认success
        duration: 1500   // 提示窗停留时间，默认1500ms
      })
      return false;
    }
    wx.navigateTo({
      url: '/pages/storedValueCard/storedValueCard',
    })
  },
  mentionCarOrder:function(){
    wx.navigateTo({
      url: '/pages/mentionCarOrder/mentionCarOrder',
    })
  },
  // 弹出
  modal_s: function (e) {
    this.setData({
      choo_modal: "block",
      //z:true
    });
  },
  //消失
  modal_n: function () {
    console.info(this.data.img);
    if (this.data.img == 1) {
      wx.navigateTo({
        url: '/pages/communityGroupPickUp/communityGroupPickUp',
      })
    } else {
      var that = this;
      console.info(1111);
      wx.scanCode({
        success: (res) => {
          var result = res.result;
          console.info(res);
          wx.navigateTo({
            url: '/pages/communityGroupOrderVerification/communityGroupOrderVerification?code=' + res.result,
          })
        },
        fail: function (res){
          console.info(res.errMsg);
        }
      })
    }
    this.setData({
      choo_modal: "none",
      //z:false
    });
  },
  //消失
  modal_n1: function () {
    this.setData({
      choo_modal: "none",
      //z:false
    });
  },
  // 弹出
  modal_s_code: function (e) {
    this.setData({
      choo_modal_code: "block",
      //z:true
    });
  },
  //消失
  modal_n_code: function () {
    this.setData({
      choo_modal_code: "none",
    });
  },
  chooseThis: function (e) {
    if (e.currentTarget.dataset.index == 1) {
      this.setData({
        giftCardWay: 1,
      });
    } else {
      this.setData({
        giftCardWay: 0,
      });
    }
    this.setData({
      img: e.currentTarget.dataset.index,
    });
  },
  shopApplyFor:function(res){
    wx.navigateTo({
      url: '/pages/interests/interests?type=' + res.currentTarget.dataset.type,
    })
  },
  toLeave:function(){
    if (this.data.quitCommunityHeadHis == 1) {
      wx.navigateTo({
        url: '/pages/leave/leave',
      })
    } else {
      wx.showToast({
        title: "审核中",
        icon: "none"
      })
    }
    
  }
})